﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;
using WP.Controls;
using WP.Controls.GridColumn;


using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;

namespace WP.RM.Form
{
    public partial class frmRMCategorySetBOMHdrMtn : BaseMtn 
    {
        public frmRMCategorySetBOMHdrMtn()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
        }

        #region Define Variable
        private bool mblnSettingStatus = false;
        private bool[] mDtlColumnReadOnlyArray;
        private bool[] mDtlColumnReadOnlyArray_LabourCost;
        private bool m_bCanTrigerCellValueChangedEven = false;
        private bool m_bCanTrigerCellValueChangedEven_LabourCost = false;
        private bool m_bSettingStatus = false;
        private bool m_bDtlChanged = false;
        private bool m_bDtlChanged_LabourCost = false;
        private DBAccess mdbcon = new DBAccess(false, false);
        private frmWKParameter frmParameter = new frmWKParameter (); 
        private System.Windows.Forms.DataGridView.HitTestInfo mhtiDtl = null;
        private enum DtlCol
        {
            RowSeqNo = 0,
            SeqNo,
            WKID,
            WKName,
            WKRemark,
            IsKeyWK,
            IsInputWK,
            CatetoryID,
            CategoryName,        
            SetID,
            SetName,
            FItemID,
            ItemNo,
            ItemName,
            SupNo,
            SupName,
            Price,
            PriceUnit,
            /// <summary>
            ///定额数量
            /// </summary>
            Qty,
            /// <summary>
            /// 损耗率 
            /// </summary>
            WastageRate, 
            /// <summary>
            /// 损耗数量
            /// </summary>
            QtyWastage,  
            /// <summary>
            /// 定额成本
            /// </summary>
            DetailCost,  
            /// <summary>
            /// 人工成本
            /// </summary>
            LabourCost,  
            /// <summary>
            /// 总成本
            /// </summary>
            TotalCost,        
            RecID,
            ValueChanged,
            HdrSeqNo,
            DelButton           
        }

        private enum LabourCostCol
        {
            RowSeqNo =0,
            SeqNo,
            WKID,
            WKName,
            /// <summary>
            /// 工价类别
            /// </summary>
            WKPriceType,
            WKRemark,
            IsKeyWK,
            /// <summary>
            /// 工序产出
            /// </summary>
            WKOutName,
            CategoryID,
            CategoryName,
            SetID,
            SetName,
            /// <summary>
            ///K3 物料内码
            /// </summary>
            FItemID,
            ItemNo,
            ItemName,
            CalUnit,
            /// <summary>
            /// 分切系数
            /// </summary>
            CutType,
            /// <summary>
            /// 总数量
            /// </summary>
            TotalQty, 
            /// <summary>
            /// 10小时额定产量
            /// </summary>
            StandardQty, 
            /// <summary>
            /// 预计用工时间
            /// </summary>
            UsedHours,   
            /// <summary>
            /// 固定工资
            /// </summary>
            StandardWage,  
            /// <summary>
            /// 26天标准工资
            /// </summary>
            StandardWage26, 
            /// <summary>
            /// 记件工价
            /// </summary>
            UnitCost,   
            /// <summary>
            /// 计件工资
            /// </summary>
            TotUnitCost,          
            /// <summary>
            /// 人工成本 = 总工价*数量 //总工价来自于工时费用标准 TotUnitCost
            /// </summary>
            DtlLaborTotCost,
            /// <summary>
            /// 工时费用标准
            /// </summary>
            WorkCost,    
            /// <summary>
            /// 备注
            /// </summary>
            Remark,         
            RecID,
            ValueChanged,
            DelButton    
        }
        #endregion

        #region ***Form Events

        private void frmRMCategorySetBOMMtn_Load(object sender, EventArgs e)
        {
            this.TableName = "rmCategorySetBOMHdr";
            //dgList.ColumnWidth = "0,70,180,100,40,20,120,90,130";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;

            FillLookUpInfo();

            frmParameter.TopMost = true  ;
            frmParameter.TopLevel = false;
            frmParameter.Dock = DockStyle.Fill;
            frmParameter.FormBorderStyle = FormBorderStyle.None;            
            frmParameter.Show();
            pnlParameter.Controls.Add(frmParameter);
            FillTree();
            
        }
        private void frmRMCategorySetBOMMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvBOM  );
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvLabourCost);
        }

        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }




            bool blnRet = false;
            if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvBOM.Name))
            {
                blnRet = dgvBOM_KeyDownEvent (keyData);
            }
            else if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvLabourCost.Name))
            {
                blnRet = dgvLabourCost_KeyDownEvent(keyData);
            }
            if (!blnRet)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return blnRet;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!this.UpdateData()) return;
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DBAccess dbcon = new DBAccess(false, false);
            DataRow dr = dbcon.GetDataFirstRow("select top 1 * from " + this.TableName + " where  RecID='"+ this.RecID +"'");
            if (dr != null)
            {
                this.TimeStamp = (byte[])dr["RecStamp"];
            }
            dbcon.CloseCon();
            if (!this.DeleteData()) return;
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab == tbpOverview)
            {
                base.ExportToExcel(dgList);
            }
            else
            {
                string strSQL = "";
                strSQL = "select * from rmCategorySetBOMHdr where recid ='" + this.m_lRecId + "'";
                DataRow drHdr = mdbcon.GetDataFirstRow(strSQL);
                if (drHdr == null) return;

                BOMToExcel.ToExcel_BOM(mdbcon, BOMToExcel.BOMType.CategorySetBOM, drHdr);
            }
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText = "定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText = "定位到下一页";
                this.btnPrev.ToolTipText = "定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText = "定位到末记录";
                this.btnTop.ToolTipText = "定位到首记录";
                this.btnNext.ToolTipText = "定位到下一条记录";
                this.btnPrev.ToolTipText = "定位到上一条记录";
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && dgList.CurrentRow != null)
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;

            //below is some speci field , need do some speci work
            if (con.Name == txtCategoryName.Name)
            {
            }
        }
        
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);
            if (this.formStatus == FormStatus.Delete) return;
            if (this.formStatus == FormStatus.Loading) return;
            Control con = sender as Control;
            WP.Controls.TextRadioBox conYESNo = sender as WP.Controls.TextRadioBox;
            if (con == null) return;

            if (conYESNo != null)
            {
                if (con.Name == utrapproval1.Name)
                {
                    if (CvtFunc.ToBoolean(utrapproval1.Text) && this.formStatus == FormStatus.AddNew)
                    {
                        MsgBoxEx.Show("BOM单还没有完成，不能审核。", SysVar.WarnTitle);
                        utrapproval1.Text = "No";
                        return;
                    }
                    else
                    {
                        ApprovalCategoryBOM(utrapproval1);
                    }
                }
                else if (con.Name == utrapproval2.Name || con.Name == utrapproval3.Name || con.Name == utrapproval4.Name || con.Name == utrapproval5.Name)
                {
                    ApprovalCategoryBOM(conYESNo);
                }
            }
        }

        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }
      
        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }
            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);
            }

            if ( e.TabPage == tbpOverview || e.TabPage == tbpGeneral || e.TabPage == tbpParameter  ) 
            {
                this.btnTallyCalculate.Visible = false;               
            }
            
            
            if (this.formStatus == FormStatus.AddNew)
            {
                if (this.UpdateData())
                {
                    if (txtCategoryID.Text != "" && txtSetID.Text != "")
                    {
                        InitGridDtl();
                        FillDtl(txtCategoryID.Text, txtSetID.Text);

                        InitGridDtlLabourCost();
                        FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text);
                    }
                }
            }
            this.btnTallyCalculate.Visible = true;


            SetControlByApproLevel();
        }

       
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #endregion Form Events***

        #region ***Form Functions

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
            string strErrMsg = "";

            if (this.formStatus != FormStatus.AddNew)
            {
                if (this.dgvBOM.CurrentRow != null)
                {
                    this.dgvBOM.EndEdit();
                    if (!CheckDtlRow(ref strErrMsg))
                    {
                        MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                        return false;
                    }
                    else
                    {
                        Update_Detail(this.dgvBOM.CurrentRow);
                    }
                }
                if (this.dgvLabourCost.CurrentRow != null)
                {
                    this.dgvLabourCost.EndEdit();
                    if (!CheckDtlRow_LabourCost(ref strErrMsg))
                    {
                        if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) != "")
                        {
                            MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                            return false;
                        }
                    }
                    else
                    {
                        Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                    }
                }
            }
            if (base.ConfirmChange())
            {
                bUpdateResult = base.UpdateData();
            }
            frmParameter.UpdateContent();

            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();


            RM.BusinessRule.RMCategorySetBOMHdrBRL mBRL = new WP.RM.BusinessRule.RMCategorySetBOMHdrBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;

        }
        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }
        public override void SetButtonStatus()
        {
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnTallyCalculate.Enabled = false ;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false ;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnAddLine.Enabled = true;
                    this.btnTallyCalculate.Enabled = true;
                    this.btnCopyTo.Enabled = true;
                    this.btnCopyBOMToLabour.Enabled = true;
                    break;
                case FormStatus.Loading:
                    break;

            }

            this.btnToExcel.Visible = SysVar.AbleToExcel; // (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            this.btnToExcel.Enabled = true ;
            //this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;
            this.btnTallyCalculate.Enabled = CvtFunc.ToBoolean(DataFunctions.GetFieldValue(mdbcon, "muser", "AbleToChangeBOMFormula", "username='" + SysVar.UserName + "'"));
            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;
            this.btnApprovalHistory.Enabled = true; 
            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;

            this.btnTop.Visible  = false ;
            this.btnBottom.Visible = false;
            this.btnPrev.Visible = false;
            this.btnNext.Visible = false;

            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;
           
           
           
        }

     
        public override void SetOtherStatus()
        {
            mblnSettingStatus = true;
            pnlParameter.Enabled = true;
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtCategoryName.Focus();
                    break;
                case FormStatus.Delete:
                    break;
                case FormStatus.Query:
                    //pnlParameter.Enabled = true;
                    //frmParameter.Enabled = false;
                    break;
                case FormStatus.Update:
                   // pnlParameter.Enabled = true;
                    //frmParameter.Enabled = false;

                    break;
                case FormStatus.Loading:
                    break;
            }

            if (this.formStatus == FormStatus.AddNew)
            {
                grpApproval.Enabled = false;
            }
            else
            {
                grpApproval.Enabled = true;
                SetApprovalControlEnable();
            }

           
            mblnSettingStatus = false;
        }

        public override void ShowBaseData()
        {
            base.ShowBaseData();
            if (this.formStatus == FormStatus.Update)
            {
                txtSetName.Text = DataFunctions.GetFieldValue("rmSet", "SetName", "SetID='" + txtSetID.Text + "'");
                txtCategoryName.Text = DataFunctions.GetFieldValue("rmCategory", "CategoryName", "CategoryID='" + txtCategoryID.Text + "'");
            }
        }

        protected override void ShowOtherData()
        {
            base.ShowOtherData();
            //frmParameter = new frmWKParameter(m_lRecId.ToString());
            if (txtCategoryID.Text == "" && txtSetID.Text == "") return; 
            if (this.formStatus != FormStatus.Delete  )
            {
                frmParameter.FillContent(m_lRecId.ToString());

                InitGridDtl();
                FillDtl(txtCategoryID.Text, txtSetID.Text);


                InitGridDtlLabourCost();
                FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text); 
            }
           
        }
        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("CategoryName", "rmCategory", "CategoryName", "ubtCategoryName");
            SetFieldLookUpInfo("CategoryID", "rmCategory", "CategoryID", "ubtCategoryName");
            SetFieldLookUpInfo("SetName", "rmSet", "SetName", "ubtSetName");
            SetFieldLookUpInfo("SetID", "rmSet", "SetID", "ubtSetName");
        }

        #endregion Form Functions***


        #region BOM Grid
        private void InitGridDtl()
        {
            // RowSeqNo = 0,SeqNo,WKName,WKRemark,CategoryName,SetName
            // IsKeyWK,  ItemNo, ItemName, Price, PriceUnit,
            // Qty, WastageRate, RatedCost,LabourCost, TotalCost,         
            this.dgvBOM.Columns.Clear();
            this.dgvBOM.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false ;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 150;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编号";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width =80;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编号";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 70;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = true ;
            colKeyWK.Visible = false;
            colKeyWK.Resizable = DataGridViewTriState.False;

            DataGridViewCheckBoxColumn colInputWK = new DataGridViewCheckBoxColumn();
            colInputWK.HeaderText = "投料工序";
            colInputWK.Width = 70;
            colInputWK.Name = "isInputWK";
            colInputWK.ReadOnly = true;
            colInputWK.Visible = false;
            colInputWK.Resizable = DataGridViewTriState.False;

             //ItemNo, ItemName, Price, PriceUnit,Qty, WastageRate,

            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "序号";
            colFItemID.Visible = false ;
            colFItemID.Name = "FItemID";
            colFItemID.Width = 50;
            colFItemID.ReadOnly = true;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "材料代码";
            colItemNo.Width = 100;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "材料名称";
            colItemName.Visible = true;
            colItemName.Width = 120;
            colItemName.ReadOnly = true; 
            colItemName.Name = "ItemName";

            TextLookUpColumn colSupNo = new TextLookUpColumn();
            colSupNo.HeaderText = "供应商代码";
            colSupNo.Width = 100;
            colSupNo.Name = "SupNo";
            colSupNo.Visible = false;
            colSupNo.ReadOnly = false;

            DataGridViewTextBoxColumn colSupName = new DataGridViewTextBoxColumn();
            colSupName.HeaderText = "供应商名称";
            colSupName.Visible = true;
            colSupName.Width = 120;
            colSupName.Visible = false;
            colSupName.Name = "SupName";

            DataGridViewTextBoxColumn colPrice = new DataGridViewTextBoxColumn();
            colPrice.HeaderText = "单价";
            colPrice.Visible = true;
            colPrice.Width = 80;
            colPrice.Name = "Price";
            colPrice.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colPrice.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 

            DataGridViewTextBoxColumn colPriceUnit = new DataGridViewTextBoxColumn();
            colPriceUnit.HeaderText = "单位";
            colPriceUnit.Visible = true;
            colPriceUnit.Width = 60;
            colPriceUnit.Name = "PriceUnit";

            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "定额数量";
            colQty.Width = 70;
            colQty.Visible = false;
            colQty.Name = "Qty";
            colQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWastageRate = new DataGridViewTextBoxColumn();
            colWastageRate.HeaderText = "损耗率%";
            colWastageRate.Visible = true;
            colWastageRate.Width = 50;
            colWastageRate.Name = "WastageRate";
            colWastageRate.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWastageRate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // QtyWastage,DetailCost,LabourCost, TotalCost,
            DataGridViewTextBoxColumn colQtyWastage = new DataGridViewTextBoxColumn();
            colQtyWastage.HeaderText = "损耗数量";
            colQtyWastage.Visible = false ;
            colQtyWastage.Width = 70;
            colQtyWastage.Name = "QtyWastage";
            colQtyWastage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQtyWastage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailCost = new DataGridViewTextBoxColumn();
            colDetailCost.HeaderText = "定额成本";
            colDetailCost.Visible = false;
            colDetailCost.Width = 70;
            colDetailCost.Name = "DetailCost";
            colDetailCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colLabourCost = new DataGridViewTextBoxColumn();
            colLabourCost.HeaderText = "人工成本";
            colLabourCost.Visible = false ;
            colLabourCost.Width = 70;
            colLabourCost.Name = "LabourCost";
            colLabourCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colLabourCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotalCost = new DataGridViewTextBoxColumn();
            colTotalCost.HeaderText = "总单价";
            colTotalCost.Visible = false ;
            colTotalCost.Width = 80;
            colTotalCost.Name = "TotalCost";
            colTotalCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";


            DataGridViewTextBoxColumn colHdrSeqNo = new DataGridViewTextBoxColumn();
            colHdrSeqNo.HeaderText = "CategoryWKHdrSeqNo";
            colHdrSeqNo.Visible = false;
            colHdrSeqNo.Name = "CategoryWKHdrSeqNo";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            colItemName.ReadOnly = true;
            colSupNo.ReadOnly = true;
            colSupName.ReadOnly = true;

            this.dgvBOM.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colSeqNo, colWKID  ,colWKName, colWKRemark, colKeyWK, colInputWK, colCategoryID  ,colCategoryName, colSetID ,colSetName ,
                                                                    colFItemID,colItemNo, colItemName, colSupNo,colSupName , colPrice, colPriceUnit,colQty, colWastageRate,
                                                                    colQtyWastage,colDetailCost,colLabourCost, colTotalCost,
                                                                    colRecID, colValueChanged,colHdrSeqNo, colDel  });

            mDtlColumnReadOnlyArray = new bool[dgvBOM.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvBOM.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvBOM.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvBOM.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvBOM.Columns.Count) dgvBOM.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvBOM.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvBOM.RowTemplate.Height = 20;
            this.dgvBOM.RowHeadersWidth = 23;
            this.dgvBOM.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvBOM.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvBOM.ColumnHeadersHeight = 30;
            this.dgvBOM.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvBOM.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvBOM.AllowUserToResizeRows = false;

        }
        private void InitGridDtlLabourCost()
        {
            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName                          
            try
            {
                this.dgvLabourCost.Columns.Clear();
                this.dgvLabourCost.Rows.Clear();
            }
            catch (Exception ex)
            {
               //
            }
            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 150;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;

            DataGridViewListColumn colWKPriceType = new DataGridViewListColumn();
            colWKPriceType.HeaderText = "工价类别";
            colWKPriceType.Width = 100;
            colWKPriceType.Name = "WKPriceType";
            colWKPriceType.ReadOnly = true ;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 70;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = false ;
            colKeyWK.Visible = true;
            colKeyWK.Resizable = DataGridViewTriState.False;
            
            DataGridViewTextBoxColumn colWKOutName = new DataGridViewTextBoxColumn();
            colWKOutName.HeaderText = "工序产出";
            colWKOutName.Width = 70;
            colWKOutName.Name = "WKOutName";
            colWKOutName.ReadOnly = true ;
            
            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编号";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 80;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编号";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;


            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "序号";
            colFItemID.Visible = false;
            colFItemID.Name = "FItemID";
            colFItemID.Width = 50;
            colFItemID.ReadOnly = false;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "加工物料代码";
            colItemNo.Width = 80;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;
            colItemNo.Visible = false;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "加工物料名称";
            colItemName.Width = 80;
            colItemName.Name = "ItemName";
            colItemName.ReadOnly = true;
            colItemName.Visible = false;

            //CalUnit,CutType, TotalQty,    //总数量            
            TextLookUpColumn colCalUnit = new TextLookUpColumn();
            colCalUnit.HeaderText = "计件单位";
            colCalUnit.Width = 100;
            colCalUnit.Name = "CalUnit";
            colCalUnit.ReadOnly = false;

            TextLookUpColumn colCutType = new TextLookUpColumn();
            colCutType.HeaderText = "分切系数";
            colCutType.Visible = true;
            colCutType.Width = 60;
            colCutType.Name = "CutType";

            DataGridViewTextBoxColumn colTotalQty = new DataGridViewTextBoxColumn();
            colTotalQty.HeaderText = "总数量";
            colTotalQty.Width = 70;
            colTotalQty.Visible = false ;
            colTotalQty.Name = "TotalQty";
            colTotalQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资          
            DataGridViewTextBoxColumn colStandardQty = new DataGridViewTextBoxColumn();
            colStandardQty.HeaderText = "额定产量(10小时)";
            colStandardQty.Visible = true;
            colStandardQty.Width = 60;
            colStandardQty.Name = "StandardQty";

            DataGridViewTextBoxColumn colSpendHours = new DataGridViewTextBoxColumn();
            colSpendHours.HeaderText = "耗用工时";
            colSpendHours.Visible = false ;
            colSpendHours.Width = 50;
            colSpendHours.Name = "SpendHours";
            colSpendHours.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSpendHours.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colStandardWage = new DataGridViewTextBoxColumn();
            colStandardWage.HeaderText = "固定工资";
            colStandardWage.Visible = true;
            colStandardWage.Width = 80;
            colStandardWage.Name = "StandardWage";
            colStandardWage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //Remark,         //备注 
            DataGridViewTextBoxColumn colStandardWage26 = new DataGridViewTextBoxColumn();
            colStandardWage26.HeaderText = "标准工资(26天)";
            colStandardWage26.Visible = true ;
            colStandardWage26.Width = 70;
            colStandardWage26.Name = "StandardWage26";
            colStandardWage26.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage26.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colUnitCost = new DataGridViewTextBoxColumn();
            colUnitCost.HeaderText = "计件工价";
            colUnitCost.Visible = false ;
            colUnitCost.Width = 70;
            colUnitCost.Name = "UnitCost";
            colUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotUnitCost = new DataGridViewTextBoxColumn();
            colTotUnitCost.HeaderText = "计件工资";
            colTotUnitCost.Visible = false;
            colTotUnitCost.Width = 70;
            colTotUnitCost.Name = "TotUnitCost";
            colTotUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDtlLaborTotCost = new DataGridViewTextBoxColumn();
            colDtlLaborTotCost.HeaderText = "人工成本";
            colDtlLaborTotCost.Visible = false ;
            colDtlLaborTotCost.Width = 70;
            colDtlLaborTotCost.Name = "";
            colDtlLaborTotCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDtlLaborTotCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWorkCost = new DataGridViewTextBoxColumn();
            colWorkCost.HeaderText = "工时费用标准";
            colWorkCost.Visible = true;
            colWorkCost.Width = 70;
            colWorkCost.Name = "WorkCost";
            colWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            
            DataGridViewTextBoxColumn colRemark = new DataGridViewTextBoxColumn();
            colRemark.HeaderText = "备注";
            colRemark.Visible = true;
            colRemark.Width = 80;
            colRemark.Name = "Remark";
            colRemark.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colRemark.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName   
            //CalUnit,CutType, TotalQty,    //总数量 
            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资   
            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //TotUnitCost      //计件工资
            //Remark,         //备注 
            this.dgvLabourCost.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colSeqNo, colWKID ,colWKName, colWKPriceType, colWKRemark, colKeyWK,colWKOutName , colCategoryID ,colCategoryName, colSetID ,colSetName , colFItemID , colItemNo,colItemName,
                                                                    colCalUnit , colCutType  , colTotalQty , colStandardQty  ,colSpendHours, colStandardWage  ,
                                                                    colStandardWage26, colUnitCost,colTotUnitCost,colDtlLaborTotCost,colWorkCost , colRemark ,
                                                                    colRecID, colValueChanged, colDel  });

            mDtlColumnReadOnlyArray_LabourCost  = new bool[dgvLabourCost.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvLabourCost.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvLabourCost.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray_LabourCost[i] = dgvLabourCost.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvLabourCost.Columns.Count) dgvLabourCost.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvLabourCost.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvLabourCost.RowTemplate.Height = 20;
            this.dgvLabourCost.RowHeadersWidth = 23;
            this.dgvLabourCost.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvLabourCost.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvLabourCost.ColumnHeadersHeight = 40;
            this.dgvLabourCost.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvLabourCost.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvLabourCost.AllowUserToResizeRows = false;

        }
        private void AddDtlRow(string strGridName)
        {
            AddDtlRow(strGridName, -1);
        }

        private void RefershRowSeqNo()
        {
            DBAccess dbCon = new DBAccess(false, false);
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                foreach (DataGridViewRow dgvRow in this.dgvBOM.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvBOM.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            string strSQL = "update rmCategorySetBOMDetail set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)DtlCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvLabourCost.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            string strSQL = "update rmCategorySetBOMLabourCost set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)LabourCostCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            dbCon.CloseCon(); 
            this.dgvBOM.EndEdit();
        }

        private void AddDtlRow(string strGridName, double iRow)
        {

            if (strGridName == dgvBOM.Name)
            {
                if (this.dgvBOM.ReadOnly) return;
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvBOM.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvBOM.Rows.Add();
                    intRow = this.dgvBOM.Rows.Count - 1;
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmCategorySetBOMDetail", "max(SeqNo)", "CategoryName='" + txtCategoryName.Text + "' and SetName='"+ txtSetName.Name +"'")) + 1);
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CategoryName].Value = txtCategoryName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetName].Value = txtSetName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CatetoryID].Value = txtCategoryID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetID].Value = txtSetID.Text;

                dgvBOM.Rows[intRow].Cells[(int)DtlCol.IsKeyWK].Value = "false";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.IsInputWK].Value = "false";
                //if (dgvBOM.Rows.Count > 0 && intRow >=1)
                //{

                //    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvBOM.Rows[intRow-1].Cells[(int)DtlCol.WKRemark].Value;
                //    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvBOM.Rows[intRow-1].Cells[(int)DtlCol.WKName].Value;
                //}
                //else
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKID].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = "";
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemNo].Value ="";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemName].Value ="";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.LabourCost].Value ="0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Price].Value ="0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.PriceUnit ].Value ="";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Qty].Value ="0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.QtyWastage].Value ="0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.DetailCost].Value = "0.00"; 
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.TotalCost].Value ="0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.WastageRate ].Value ="0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value = -1;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.HdrSeqNo].Value = "-1"; 
                dgvBOM.CurrentCell = dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName];
                m_bCanTrigerCellValueChangedEven = true;
              
            }
            else if (strGridName == this.dgvLabourCost.Name)
            {
                if (this.dgvLabourCost.ReadOnly) return;
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven_LabourCost  = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvLabourCost.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvLabourCost.Rows.Add();
                    intRow = this.dgvLabourCost.Rows.Count - 1;
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmCategorySetBOMLabourCost", "max(SeqNo)", "CategoryName='" + txtCategoryName.Text + "' and SetName='" + txtSetName.Name + "'")) + 1);
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryName].Value = txtCategoryName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetName].Value = txtSetName.Text;

                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryID].Value = txtCategoryID.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetID].Value = txtSetID.Text;

                string strBOMSeqNo = "0";
                string strItemNo = "";
                if (dgvBOM.CurrentRow != null)
                {                    
                    strItemNo = CvtFunc.ToString(dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemNo].Value = "";// strItemNo;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemName].Value = "";//DataFunctions.GetFieldValue("iminvmaster", "itemname", "itemno='" + strItemNo + "'");
                //if (dgvLabourCost.Rows.Count > 0 && intRow >=1)
                //{

                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKRemark].Value;
                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKName].Value;
                //}
                //else
                {
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKRemark].Value = "";
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName].Value = "";
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CalUnit].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CutType].Value = "1";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardQty ].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage ].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage26 ].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty ].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UnitCost ].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UsedHours ].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty ].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WorkCost].Value = txtWorkCost.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.Remark].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RecID].Value = -1;
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                dgvLabourCost.CurrentCell = dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName];
                m_bCanTrigerCellValueChangedEven_LabourCost = true;
            }
            RefershRowSeqNo();
        }

        private bool CheckDtlRow(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvBOM.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlRow_LabourCost(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvLabourCost.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell_LabourCost(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlCell(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvBOM.CurrentRow != null && this.dgvBOM.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvBOM.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
                case DtlCol.ItemNo :
                    if (strValue.Trim() == "" && CvtFunc.ToBoolean ( this.dgvBOM.CurrentRow.Cells [(int)DtlCol.IsInputWK].Value  ))
                    {
                        strErrMsg = "投料工序的物料名称不能为空";
                        return false;
                    }
                    else if (!DataFunctions.CheckRecordExist ("iminvmaster", strValue,"ItemNo") && strValue !="")
                    {
                        strErrMsg ="不存在的物料编码";
                        return false ;
                    }
                    return true;
            }
            return bReturnValue;
        }
        private bool CheckDtlCell_LabourCost(int iColumn, ref string strErrMsg)
        {
            if (this.formStatus == FormStatus.Loading) return true;
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvLabourCost.CurrentRow != null && this.dgvLabourCost.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvLabourCost.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }
        private void btnAddLine_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab  == tbpBOM)
            {
                string strErrMsg = string.Empty;
                if (this.dgvBOM.Rows.Count  == 0)
                {
                    AddDtlRow(this.dgvBOM.Name );
                }
                else if (CheckDtlRow(ref strErrMsg))
                {
                    if (Update_Detail(this.dgvBOM.CurrentRow))
                    {
                        AddDtlRow(this.dgvBOM.Name, dgvBOM.CurrentCell.RowIndex);
                    }
                    //foreach (DataGridViewRow dgvRow in this.dgvBOM.Rows)
                    //{
                       
                    //    if (CheckDtlRow(ref strErrMsg))
                    //    {
                    //        Update_Detail(dgvRow);
                    //    }
                    //}

                }
                else if (!string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                string strErrMsg = string.Empty;
                if (this.dgvLabourCost.Rows.Count == 0)
                {
                    AddDtlRow(this.dgvLabourCost.Name);
                }
                else if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow))
                    {
                        AddDtlRow(this.dgvLabourCost.Name, dgvLabourCost.CurrentCell.RowIndex);
                    }
                }
                else if (!string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private bool Update_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            if (dgvBOM.ReadOnly == true) return true;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                RefershRowSeqNo();
                dbcon.BeginTran();
                RMCategorySetBOMHdrBRL rmBRL = new RMCategorySetBOMHdrBRL();                
                DataRow drBOM = dbcon.GetDataSet("select * from rmCategorySetBOMDetail").Tables[0].NewRow(); 
                BaseFunctions.FillDataRowByGridRow(dgvRow, drBOM);
                drBOM["CategoryID"] = txtCategoryID.Text;
                drBOM["SetID"] = txtSetID.Text;
                
                if (rmBRL.UpdateDetailValid(dbcon , drBOM))
                {
                    dbcon.CommitTran();
                }
                else
                {
                    dbcon.RollbackTran(); 
                }

                dgvRow.Cells[(int)DtlCol.RecID].Value = CvtFunc.ToString ( drBOM["RecID"]);
                dgvRow.Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(drBOM["DetailCost"], "Ns.4");
                dgvRow.Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(drBOM["TotalCost"] ,"Ns.2");
                dgvRow.Cells[(int)DtlCol.ValueChanged].Value = "0";
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
                dgvBOM.EndEdit();
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran(); 
                return false;
            }
            dbcon.CloseCon();
            return true;
        }

        private bool Update_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            if (this.dgvLabourCost.ReadOnly) return false; 
            DBAccess dbcon = new DBAccess(false, false);
            try
            {

                dbcon.BeginTran();
                RMCategorySetBOMHdrBRL rmBRL = new RMCategorySetBOMHdrBRL();
                DataRow drLabourCost = dbcon.GetDataSet("select * from rmCategorySetBOMLabourCost").Tables[0].NewRow();
                BaseFunctions.FillDataRowByGridRow(dgvRow, drLabourCost);
                drLabourCost["CategoryID"] = txtCategoryID.Text;
                drLabourCost["SetID"] = txtSetID.Text;
                if (rmBRL.UpdateDetailValid_LabourCost(dbcon, drLabourCost))
                {
                    dbcon.CommitTran();
                }
                else
                {
                    dbcon.RollbackTran();
                }

                dgvRow.Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToString(drLabourCost["RecID"]);
                dgvRow.Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(drLabourCost["UnitCost"], "Ns.4");
                dgvRow.Cells[(int)LabourCostCol.TotUnitCost].Value = BaseFunctions.FormatNumeric(drLabourCost["TotUnitCost"], "Ns.4");
                dgvRow.Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(drLabourCost["SpendHours"], "Ns.6");
                //dgvRow.Cells[(int)LabourCostCol.DtlLaborTotCost].Value = BaseFunctions.FormatNumeric(drLabourCost["DetailCost"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
                dgvLabourCost.EndEdit();
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
                return false;
            }
            this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
            dbcon.CloseCon();
            return true;
        }

        private bool Delete_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            RMCategorySetBOMHdrBRL rmCategory = new RMCategorySetBOMHdrBRL();
            DBAccess dbcon = new DBAccess(false, false);
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)DtlCol.RecID].Value );
            rmCategory.DeleteDetail( dbcon, strRecID );
            return true;
        }

        private bool Delete_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            RMCategorySetBOMHdrBRL rmBOM = new RMCategorySetBOMHdrBRL();
            DBAccess dbcon = new DBAccess(false, false);
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)LabourCostCol.RecID].Value);
            rmBOM.DeleteDetail_LabourCost(dbcon, strRecID);
            return true;
        }

        private void FillDtl(string strCategoryID,string strSetID)
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven = false;

            this.dgvBOM.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);
             string strCategoryName = DataFunctions.GetFieldValue(dbCon, "rmCategory","CategoryName","CategoryID='"+ strCategoryID +"'");
             string strSetName = DataFunctions.GetFieldValue(dbCon, "rmSet", "SetName", "SetID='" + strSetID + "'");
            strSql = "select A.* from rmCategorySetBOMDetail A  where A.categoryID='" + strCategoryID + "' and A.SetID='" + strSetID + "' order by A.RowSeqNo,A.SeqNo,A.WKName desc";
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            if (mUserAlertTable.Rows.Count == 0)
            {
                strSql = "select * from rmCategoryWK where CategoryID='"+ strCategoryID  +"' ";
                mUserAlertTable = dbCon.GetDataTable(strSql);
                foreach (DataRow drDtl in mUserAlertTable.Rows)
                {
                    this.dgvBOM.Rows.Add();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SeqNo].Value = drDtl["SeqNo"].ToString().TrimEnd();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKID].Value = drDtl["WKProductID"].ToString().TrimEnd();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CatetoryID].Value = drDtl["CategoryID"].ToString().TrimEnd();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetID].Value = txtSetID.Text ;
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue(dbCon, "rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + drDtl["WKProductID"] + "'");
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsKeyWK].Value = CvtFunc.ToBoolean(drDtl["IsKeyWK"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsInputWK].Value = CvtFunc.ToBoolean(drDtl["IsInputWK"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.HdrSeqNo].Value = CvtFunc.ToString(drDtl["SeqNo"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryName].Value =strCategoryName ;
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetName].Value = strSetName ; 
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value ="0";
                    this.dgvBOM.EndEdit();
                   
                    Update_Detail(dgvBOM.Rows[dgvBOM.Rows.Count - 1]);
                }
            }
            else 
            {
                for (int i = 0; i < mUserAlertTable.Rows.Count; i++)
                {
                    DataRow dr = mUserAlertTable.Rows[i];
                    if (this.dgvBOM.Rows.Count <= i) this.dgvBOM.Rows.Add();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKID].Value = dr["WKID"].ToString().TrimEnd();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName].Value =DataFunctions.GetFieldValue ( dbCon ,"rmWorkingProcedure","WorkingProcedureName","WorkingProcedureID='"+ dr["WKID"] +"'");
                    //dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKRemark].Value = dr["Remark"].ToString().TrimEnd();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CatetoryID].Value = dr["CategoryID"].ToString().TrimEnd();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryName].Value =strCategoryName ;
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetID].Value = CvtFunc.ToString(dr["SetID"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetName].Value = strSetName ; ;
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);
                    strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                    DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                    if (drItemNo == null)
                    {

                    }
                    else
                    {
                        dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                        dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                    }
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.LabourCost].Value = BaseFunctions.FormatNumeric(dr["LabourCost"], "Ns.2");
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Price].Value = BaseFunctions.FormatNumeric(dr["Price"], "Ns.3");
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString(dr["PriceUnit"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Qty].Value = BaseFunctions.FormatNumeric(dr["Qty"], "Ns.8");
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.QtyWastage].Value = BaseFunctions.FormatNumeric(dr["QtyWastage"], "Ns.2");
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WastageRate].Value = BaseFunctions.FormatNumeric(dr["WastageRate"], "Ns.2");
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(dr["TotalCost"], "Ns.2");
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                    //dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryName].Value = strCategoryName;
                    //dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetName].Value = strSetName;
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsKeyWK].Value = dr["IsKeyWK"].ToString();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsInputWK].Value = dr["IsInputWK"].ToString();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupNo].Value = dr["SupNo"].ToString();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupName].Value = dr["SupName"].ToString();
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.HdrSeqNo].Value = CvtFunc.ToString(dr["CategoryWKHdrSeqNo"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
                }//
            }
            if (dgvBOM.Rows.Count == 0)
            {
                AddDtlRow(this.dgvBOM.Name);
            }
            dbCon.CloseCon();
            RefershRowSeqNo(); 
            base.SetBlankImage(dgvBOM);
            m_bCanTrigerCellValueChangedEven = true;
        }

        private void FillDtl_LabourCost(string strCategoryID, string strSetID)
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven_LabourCost  = false;

            this.dgvLabourCost.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            strSql = "select A.* from rmCategorySetBOMLabourCost A  where A.categoryID='" + strCategoryID + "' and A.SetID='" + strSetID + "' order by A.RowSeqNo";
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            foreach(DataRow dr in mUserAlertTable.Rows )
            {
                this.dgvLabourCost.Rows.Add();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKID].Value = CvtFunc.ToString(dr["WKID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName].Value =DataFunctions.GetFieldValue ( dbCon ,"rmWorkingProcedure","WorkingProcedureName","WorkingProcedureID='"+ dr["WKID"] +"'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKPriceType].Value = dr["WKPriceType"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKRemark].Value = dr["WKRemark"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.IsKeyWK].Value = dr["IsKeyWK"].ToString();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryID].Value = CvtFunc.ToString(dr["CategoryID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryName].Value = DataFunctions.GetFieldValue(dbCon, "rmCategory", "CategoryName", "CategoryID='" + dr["CategoryID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetID].Value = CvtFunc.ToString(dr["SetID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetName].Value = DataFunctions.GetFieldValue(dbCon, "rmSet", "SetName", "SetID='" + dr["SetID"] + "'"); 
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);
                strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                if (drItemNo == null)
                {

                }
                else
                {
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                }
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKOutName].Value = CvtFunc.ToString(dr["WKOutName"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CalUnit ].Value = CvtFunc.ToString(dr["CalUnit"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CutType].Value = ( CvtFunc.ToString(dr["CutType"])==""?"1": CvtFunc.ToString(dr["CutType"]));
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.Remark ].Value = CvtFunc.ToString(dr["Remark"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(dr["StandardQty"], "Ns.3");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage].Value = CvtFunc.ToString(dr["StandardWage"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage26].Value = BaseFunctions.FormatNumeric(dr["StandardWage26"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(dr["TotalQty"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(dr["UnitCost"], "Ns.6");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotUnitCost].Value = BaseFunctions.FormatNumeric(dr["TotUnitCost"], "Ns.4");
                //dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.DtlLaborTotCost].Value = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(dr["SpendHours"], "Ns.6");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WorkCost ].Value = BaseFunctions.FormatNumeric(dr["WorkCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
            }
            
            if (dgvLabourCost.Rows.Count == 0)
            {
                AddDtlRow(this.dgvLabourCost.Name);
            }
            dbCon.CloseCon();
            base.SetBlankImage(dgvLabourCost);
            m_bCanTrigerCellValueChangedEven_LabourCost = true;
        }

        private void dgvBOM_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvBOM.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvBOM.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvBOM.Name );
                }
            }
            else
            {
                if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvBOM, e))
                {
                    this.dgvBOM.CurrentCell.Selected = true;
                    this.dgvBOM.CurrentCell.Selected = false;
                    if (!this.Delete_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvBOM.Rows.Remove(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]);
                    if (this.dgvBOM.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvBOM.Name);
                    }
                }
            }
        }

      
        private void dgvBOM_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvBOM.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)DtlCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell(e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvBOM_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvBOM.CurrentRow != null && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow(ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void dgvBOM_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven || e.ColumnIndex == (int)DtlCol.ValueChanged || e.ColumnIndex ==(int)DtlCol.DelButton ) return;
            dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value = "1";
            m_bDtlChanged = true;
            dgvBOM.EndEdit();
            if (e.ColumnIndex == (int)DtlCol.WKID)
            {
                string strWKID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value);
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
            }
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) == "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "'");
                }
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "Categoryname='" + txtCategoryName.Text + "' and WKName='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "'");
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsInputWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsInputWK", "Categoryname='" + txtCategoryName.Text + "' and WKName='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "'");
            }
            if (e.ColumnIndex == (int)DtlCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'");
                }            
            }
            if (e.ColumnIndex == (int)DtlCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
                string strSQL = "select * from iminvmaster where FItemID='" + strFItemID + "'";
                DataRow drItemInfo = mdbcon.GetDataFirstRow(strSQL);
                if (drItemInfo != null)
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemInfo["itemno"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString ( drItemInfo["itemname"]) ;
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = CvtFunc.ToString ( drItemInfo["SupNo"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = CvtFunc.ToString ( drItemInfo["SupName"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = CvtFunc.ToString(drItemInfo["MarketCost"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString ( drItemInfo["CostUnit"]);
                }
            }
            dgvBOM.EndEdit();
        }

        private void dgvBOM_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
            if (this.dgvBOM.CurrentRow == null) return;
            ShowFormula( this.dgvBOM,  this.dgvBOM.CurrentRow.Index);
            ChangeGridSelectRowBackColor( dgvBOM );
        }

        private void ChangeGridSelectRowBackColor( DataGridView dgvView)
        {
            foreach (DataGridViewColumn dccol in dgvView.Columns)
            {
                for (int i = 0; i <= dgvView.Rows.Count - 1; i++)
                {
                    dgvView.Rows[i].Cells[dccol.Name].Style.BackColor = Color.White;
                }
            }
            foreach (DataGridViewColumn dccol in dgvView.Columns)
            {
                dgvView.CurrentRow.Cells[dccol.Name].Style.BackColor = Color.AntiqueWhite;
            }
        }

        private void dgvBOM_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
        }

        private void dgvBOM_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvBOM.EndEdit();
            if (this.formStatus != FormStatus.Update && this.formStatus != FormStatus.AddNew) return;
            if (e.ColumnIndex == (int)DtlCol.ItemNo)
            {
                if (CvtFunc.ToString(this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ItemNo].Value) == "")  // 可能手工删除了物料
                {
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ItemName].Value = "";
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.FItemID].Value = "0";
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.PriceUnit].Value = "";
                }
            }
            else if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvBOM.Rows [e.RowIndex].Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue ( "rmCategoryWK","IsKeyWK","Categoryname='"+ txtCategoryName.Text +"' and WKName='"+ CvtFunc.ToString ( this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) +"'");
            }
           
            else if (e.ColumnIndex == (int)DtlCol.Price)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.3");
            }
            else if (e.ColumnIndex == (int)DtlCol.Qty)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.8");
            }
            else if (e.ColumnIndex == (int)DtlCol.WastageRate)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)DtlCol.DetailCost)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.4");
            }
            if (CvtFunc.ToString(dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value) == "1" && (e.ColumnIndex == (int)DtlCol.Price || e.ColumnIndex == (int)DtlCol.PriceUnit || e.ColumnIndex == (int)DtlCol.ItemNo
               || e.ColumnIndex == (int)DtlCol.Qty || e.ColumnIndex == (int)DtlCol.WastageRate || e.ColumnIndex == (int)DtlCol.LabourCost))
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow(ref strErrMsg))
                {
                    Update_Detail(this.dgvBOM.Rows[e.RowIndex]);
                }
            }
        }

        private void dgvBOM_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvBOM_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvBOM, e, (int)DtlCol.DelButton);
            string strErrMsg = "";
            if (dgvBOM.CurrentRow != null && CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }                   
                }
                else
                {
                    return;
                }
            }
        }

        private void dgvBOM_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvBOM.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvBOM.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvBOM_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvBOM.EndEdit();
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow(ref strErrMsg))
                            {

                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex > 0)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            if (dgvBOM.CurrentCell.RowIndex > 0)
                            {
                                //dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentRow.Index  - 1].Cells[(int)DtlCol.WKName];
                            }
                        }
                        else if (dgvBOM.Rows.Count > 1)
                        {

                            this.dgvBOM.Rows.Remove(this.dgvBOM.CurrentRow);
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvBOM.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvBOM);
                    if (dgvBOM.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow(ref strErrMsg))
                                {
                                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvBOM, dgvBOM.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }

       
        private void dgvBOM_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex ==(int)DtlCol.WKName && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvBOM.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvBOM.Rows.Count - 1 && dgvBOM.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() !=e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,e.CellBounds.Top, e.CellBounds.Right - 1,e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvBOM.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() ==e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2,e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }

        private void 可更改工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            string strCategoryWKHdrSeqNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.HdrSeqNo].Value);
            string strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value); 
            strSQL = "select CategoryName as 类别名称,WKName as 工序名称,RecID from dbo.rmCategoryWKAlter where hdrseqno='" + strCategoryWKHdrSeqNo + "' order by CategoryName ";
            strSQL = " select A.CategoryName as 类别名称,A.WKName as 工序名称,A.WKProductID as 工序编号,A.RecID from rmCategoryWKAlter A inner join rmCategoryWK B on a.hdrseqno=b.seqno where B.CategoryID='" + txtCategoryID.Text + "' and B.WKProductID='" + strWKName + "' ";
            strCaption = "工序选择";
            if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null) strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            strFindField = "WKProductID";
            int intCol = this.dgvBOM.CurrentCell.ColumnIndex;
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "可更改工序ToolStripMenuItem", this.dgvBOM.Name );
        }

        private void 所有工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkingProcedure");
            strCaption = "工序选择";
            if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null) strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            strFindField = "WorkingProcedureID";
            int intCol = this.dgvBOM.CurrentCell.ColumnIndex;
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField,"所有工序ToolStripMenuItem",this.dgvBOM.Name );
        }

         private void 类别工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            strSQL = "select RecID, WKProductID as 工序编号,WKName as 工序名称 from rmCategoryWK where categoryID='" + txtCategoryID.Text + "' order by WKName";
            strCaption = "类别工序选择";
            if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null) strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            strFindField = "WKProductID";
            int intCol = this.dgvBOM.CurrentCell.ColumnIndex;
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "类别工序ToolStripMenuItem", this.dgvBOM.Name);
        }
        #endregion

        #region LabourCost Grid
        private void dgvLabourCost_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvLabourCost.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvLabourCost.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex,this.dgvLabourCost.Name );
                }
            }
            else
            {
                if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvLabourCost, e))
                {
                    this.dgvLabourCost.CurrentCell.Selected = true;
                    this.dgvLabourCost.CurrentCell.Selected = false;
                    if (!this.Delete_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]);
                    if (this.dgvLabourCost.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvLabourCost.Name);
                    }
                }
            }
        }


        private void dgvLabourCost_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvLabourCost.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (CvtFunc.ToInt (dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell_LabourCost(e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvLabourCost_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvLabourCost.CurrentRow != null && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow_LabourCost(ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void dgvLabourCost_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven_LabourCost || e.ColumnIndex == (int)LabourCostCol.ValueChanged || e.ColumnIndex ==(int)LabourCostCol.DelButton ) return;
            dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ValueChanged].Value = "1";
            m_bDtlChanged_LabourCost = true;
            dgvLabourCost.EndEdit();
            if (e.ColumnIndex == (int)LabourCostCol.WKID || e.ColumnIndex ==(int)LabourCostCol.WKPriceType)
            {
                string strWKPrineType = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value);
                string strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKOutName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WKOut", "WorkingProcedureID='" + strWKID + "'");
                string strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + strWKID + "'");
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, strWKID,strWKPrineType);
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                    string strSQL = "select * from [imCategoryWKWorkCost] where CategoryID='{0}' and WKProductID='{1}' and WKPriceType='{2}'";
                    strSQL = string.Format(strSQL, txtCategoryID.Text, strWKID,strWKPrineType);
                    DBAccess dbcon = new DBAccess ( false,false );
                    DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                    if (drRow != null)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.CalUnit].Value = CvtFunc.ToString(drRow["STDQtyUnit"]);
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(drRow["WKSTDQty"], "Ns.2");
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardWage].Value = BaseFunctions.FormatNumeric(drRow["WKSalary"], "Ns.2");
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardWage26].Value = BaseFunctions.FormatNumeric(drRow["WKSTDSalary"], "Ns.2");
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(drRow["WKUnitCost"], "Ns.6");                        
                    }
                    dbcon.CloseCon(); 
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.WKName)
            {
                if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value) == "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) + "'");
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("iminvmaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID ].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = DataFunctions.GetFieldValue("iminvmaster", "itemno", "FItemID='" + strFItemID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");
            }
            dgvLabourCost.EndEdit();
        }

        private void dgvLabourCost_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
            if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
            {
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false ;
            }
            ShowFormula(this.dgvLabourCost, this.dgvLabourCost.CurrentRow.Index);
            ChangeGridSelectRowBackColor(dgvLabourCost);
        }

        private void dgvLabourCost_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
        }

        private void dgvLabourCost_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvLabourCost.EndEdit();            
            if (e.ColumnIndex == (int)LabourCostCol.UnitCost )
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.6");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.ItemNo)
            {
                if (CvtFunc.ToString(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemNo].Value) == "")
                {
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemNo].Value = "";
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemName].Value = "";
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.FItemID].Value = "0";
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.WKName)
            {
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    string strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);
                    string strWKPriceType = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value);
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, strWKID, strWKPriceType);
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardQty)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage26)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            if (CvtFunc.ToString(dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ValueChanged].Value) == "1" && (e.ColumnIndex == (int)LabourCostCol.StandardWage26 || e.ColumnIndex == (int)LabourCostCol.StandardWage
                || e.ColumnIndex == (int)LabourCostCol.StandardQty || e.ColumnIndex == (int)LabourCostCol.CalUnit))
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    Update_Detail_LabourCost(this.dgvLabourCost.Rows[e.RowIndex]);
                }
            }
        }

        private void dgvLabourCost_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvLabourCost_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvLabourCost, e, (int)LabourCostCol.DelButton);
            string strErrMsg = "";
            if (dgvLabourCost.CurrentRow != null && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
        }

        private void dgvLabourCost_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvLabourCost.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvLabourCost.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvLabourCost_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvLabourCost.EndEdit();
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow_LabourCost (ref strErrMsg))
                            {

                                if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost (ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow_LabourCost (ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex > 0)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost (ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            if (dgvLabourCost.CurrentCell.RowIndex > 0)
                            {
                                //dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentRow.Index  - 1].Cells[(int)DtlCol.WKName];
                            }
                        }
                        else if (dgvLabourCost.Rows.Count > 1)
                        {

                            this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.CurrentRow);
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvLabourCost.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvLabourCost);
                    if (dgvLabourCost.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow_LabourCost (ref strErrMsg))
                                {
                                    if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvLabourCost, dgvLabourCost.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }


        private void dgvLabourCost_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex == (int)LabourCostCol.WKName && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvLabourCost.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvLabourCost.Rows.Count - 1 && dgvLabourCost.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvLabourCost.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }


        #endregion

        private void Dtl_LookUp(int iColumnIndex,string strGridName)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            int intCol = 0;
            if (strGridName == this.dgvBOM.Name)
            {
                switch ((DtlCol)iColumnIndex)
                {
                    case DtlCol.WKName:
                        cmsWKLookup.Show(this.ActiveControl, new Point(this.ActiveControl.Top, this.ActiveControl.Left));
                        break;
                    case DtlCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL("iminvmaster"); //" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value != null) strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value.ToString();
                        
                        strFindField = "FItemID";
                        break;
                }
            }
            else
            {
                switch ((LabourCostCol)iColumnIndex)
                {
                    case LabourCostCol.WKName :
                        //strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkingProcedure");
                        //strCaption = "工序选择";
                        //if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
                        //strFindField = "WorkingProcedureName";
                        //intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                        strSQL = "select RecID,CategoryID as 类别编码,CategoryName as 类别名称,WKProductID as 工序编码,WKName as 工序名称,WKPriceType as 工价类别,WKSalary as 固定工资,WKSTDSalary as 标准工资,WorkCostRate as 工时费用标准,WKSTDQty as 额定产能,STDQtyUnit as 单位 from imCategoryWKWorkCost where CategoryID='" + txtCategoryID.Text + "' and WKProductID in ( select WorkingProcedureID from rmWorkingProcedure where FianUsed=1)";
                        break; 
                    case LabourCostCol.CalUnit :
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("imUnit");
                        strCaption = "";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value.ToString();
                        strFindField = "Unit";
                        intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                        break;
                    case LabourCostCol.CutType :
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmCutType");
                        strCaption = "分切方式选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value.ToString();
                        strFindField = "CutTimes";
                        intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                        break;
                    case LabourCostCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL("iminvmaster"); //" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value.ToString();
                        strFindField = "FItemID";
                        break;
                }
            }
            if (strSQL == "") return;
            if (mblnLookUpSortByDescription)
            {
                strSQL = DataFunctions.GetSqlByDescriptionSort(strSQL);
                mblnLookUpSortByDescription = false;
            }

            DtlLookup(iColumnIndex, strSQL, strCaption, strFindValue, strFindField, "", strGridName);
        }

        private void DtlLookup(int iColumnIndex, string strSQL, string strCaption, string strFindValue, string strFindField, string strMenuName,string strGridName)
        {
            frmLookUp frmlookup = null;
            frmLookUpItem frmlookupitem = null;
            bool blnHaveReturnValue = false;
            if ((DtlCol)iColumnIndex == DtlCol.ItemNo)
            {
                frmlookupitem = new frmLookUpItem(strSQL, strCaption, strFindValue, strFindField);
                frmlookupitem.ShowDialog();
                blnHaveReturnValue = frmlookupitem.HaveReturnValue;
            }
            else
            {
                frmlookup = new frmLookUp(strSQL, strCaption, strFindValue, strFindField);
                frmlookup.ShowDialog();
                blnHaveReturnValue = frmlookup.HaveReturnValue;
            }

            if (blnHaveReturnValue)
            {
                if (strGridName == this.dgvBOM.Name)
                {
                    switch ((DtlCol)iColumnIndex)
                    {
                        case DtlCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue(strFindField);                               
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue(strFindField);
                            }
                            else if ( strMenuName == this.所有工序ToolStripMenuItem.Name ) 
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue(strFindField);
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            break;
                        case DtlCol.ItemNo:
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value = frmlookupitem.GetReturnValue("FItemID");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = frmlookupitem.GetReturnValue("ItemNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = frmlookupitem.GetReturnValue("ItemName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = frmlookupitem.GetReturnValue("SupNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = frmlookupitem.GetReturnValue("SupName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = frmlookupitem.GetReturnValue("MarketCost");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = frmlookupitem.GetReturnValue("CostUnit");
                            break;
                    }
                }
                else
                {
                    switch ((LabourCostCol)iColumnIndex)
                    {
                        case LabourCostCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WkName");
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                            }
                            else if (strMenuName == this.所有工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value = frmlookup.GetReturnValue("WKPriceType");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value) + "'"); 
                            }
                            break;
                        case LabourCostCol.CalUnit:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value = frmlookup.GetReturnValue("Unit");
                            break;
                        case LabourCostCol.CutType  :
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value = frmlookup.GetReturnValue(strFindField);
                            break;
                        case LabourCostCol.ItemNo:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = frmlookup.GetReturnValue("FItemID");
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = frmlookup.GetReturnValue("ItemNo");
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = frmlookup.GetReturnValue("ItemName");    
                            break;
                    }
                }
            }
            if ( frmlookup !=null ) frmlookup.Close();
            if (frmlookupitem != null) frmlookupitem.Close();  
        }

        private void btnTallyCalculate_Click(object sender, EventArgs e)
        {
            if (tbcMain.SelectedTab == tbpBOM)
            {
                if (this.dgvBOM.CurrentRow == null) return;
                if (this.dgvBOM.CurrentCell == null) return;
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
                string strRecID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.FromCategorySetBOM);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                string strCaption = "定额数量  计算公式选择： " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "    " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "  " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value);
                frmCal.Text = strCaption;
                frmCal.MaximumSize = frmCal.Size;
                frmCal.ShowDialog();
                ShowFormula(this.dgvBOM,this.dgvBOM.CurrentRow.Index);
            }
            else if (tbcMain.SelectedTab == tbpOtherCost)
            {
                if (this.dgvLabourCost.CurrentRow == null) return;
                if (this.dgvLabourCost.CurrentCell == null) return;                
                string strRecID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.OtherCategorySetBOM);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                frmCal.Text = "项目分摊  计算公式选择： " + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value)  ;
                frmCal.ShowDialog();
                ShowFormula(this.dgvLabourCost, this.dgvLabourCost.CurrentRow.Index);
            }
            
        }

        private void btnCalcPrice_Click(object sender, EventArgs e)
        {
            if (this.dgvBOM.CurrentRow == null) return;
            if (this.dgvBOM.CurrentCell == null) return;
            if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
            string strRecID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value);
            frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.PriceCategorySetBOM);
            frmCal.StartPosition = FormStartPosition.CenterParent;
            frmCal.Text = "单价  计算公式选择： " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "    " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
            frmCal.ShowDialog();
        }

        private void tbcMain_SelectedIndexChanged(object sender, EventArgs e)
        {            
           
        }

        private void btnCopyTo_Click(object sender, EventArgs e)
        {
            bool blnHasReturn = false ;
            string strDestCateogory = "";
            string strDestSet ="";
            frmRMCategorySetBOMCopy frmCopy = new frmRMCategorySetBOMCopy(txtCategoryID.Text, txtSetID.Text );
            frmCopy.CopyTo(ref blnHasReturn,ref  strDestCateogory,ref  strDestSet);
            if (blnHasReturn)
            {
                DBAccess dbCon = new DBAccess(false, false);
                RMCategorySetBOMHdrDAL rmDAL = new RMCategorySetBOMHdrDAL();
                string strSQL="select * from rmCategorySetBOMHdr where CategoryID='"+ txtCategoryID.Text  +"' and SetID='"+ txtSetID.Text  +"'";
                DataRow drHdr = dbCon.GetDataFirstRow ( strSQL );
                try
                {
                    dbCon.BeginTran();
                    if (!rmDAL.CopytoNewVer(dbCon, drHdr, strDestCateogory, strDestSet))
                        dbCon.RollbackTran();
                    else
                        dbCon.CommitTran();
                }
                catch (Exception ex)
                {
                    dbCon.RollbackTran();
                }
            }
        }

        private void ShowFormula( DataGridView dgvView, int intRow)
        {
            if (dgvView.Name == dgvBOM.Name)
            {
                if (this.dgvBOM.Rows[intRow] == null) return;
                string strRecID = CvtFunc.ToString(this.dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value);
                if (CvtFunc.ToDouble(strRecID) <= 0)
                {
                    txtCalFormula.Text = "";
                    return;
                }
                txtCalFormula.Text = DataFunctions.GetFieldValue(mdbcon, "rmWKFormula", "WKFormula", "BOMRecID='" + strRecID + "'");
            }
            else
            {
                if (this.dgvLabourCost.Rows[intRow] == null) return;
                string strRecID = CvtFunc.ToString(this.dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RecID].Value);
                if (CvtFunc.ToDouble(strRecID) <= 0)
                {
                    txtCalFormula2.Text = "";
                    return;
                }
                txtCalFormula2.Text = DataFunctions.GetFieldValue(mdbcon, "rmWKFormulaOtherCategorySetBOM", "WKFormula", "BOMRecID='" + strRecID + "'");
            }
        }

        private void ubtCategoryName_Click(object sender, EventArgs e)
        {

        }

        private void frmRMCategorySetBOMHdrMtn_FormClosed(object sender, FormClosedEventArgs e)
        {
            mdbcon.CloseCon();
        }

        private void btnCopyBOMToLabour_Click(object sender, EventArgs e)
        {
            frmRMCopyBOMToLabourCost frmLabourCost = new frmRMCopyBOMToLabourCost();
            frmRMCopyBOMToLabourCost.Parameter para = new frmRMCopyBOMToLabourCost.Parameter ();
            para.strCategoryName = txtCategoryName.Text ;
            para.strSetName = txtSetName.Text ;
            para.strCategoryID = txtCategoryID.Text;
            para.strSetID = txtSetID.Text;
            frmLabourCost.ShowFrom( frmRMCopyBOMToLabourCost.FromType.Category ,this.dgvBOM, para );
            if (frmLabourCost.mblnHasReturn)
            {
                foreach (DataGridViewRow dgvRow in frmLabourCost.dgvBOM.Rows)
                {
                    if (CvtFunc.ToBoolean(dgvRow.Cells["SEL"].Value))
                    {
                        string strWKID = CvtFunc.ToString(dgvRow.Cells["WKID"].Value);
                        string strFItemID = CvtFunc.ToString(dgvRow.Cells["FItemID"].Value);
                        int intInsertRow = GetLastRowInGridForSpecilaWKName(strWKID);
                        string strErrMsg = "";
                        if (CheckDtlRow_LabourCost(ref strErrMsg))
                        {
                            AddDtlRow(this.dgvLabourCost.Name, intInsertRow);
                        }
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CategoryID].Value = dgvRow.Cells["CategoryID"].Value ;
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.SetID].Value = dgvRow.Cells["SetID"].Value;
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = CvtFunc.ToString(dgvRow.Cells["WKID"].Value);
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                        this.dgvLabourCost_CellValueChanged(this.dgvLabourCost, new DataGridViewCellEventArgs((int)LabourCostCol.WKName, this.dgvLabourCost.CurrentCell.RowIndex));
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = strFItemID;
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = DataFunctions.GetFieldValue("iminvmaster", "itemno", "FItemID='" + strFItemID + "'");
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");
                        this.dgvLabourCost.EndEdit();
                        this.Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                    }
                }
            }
            this.dgvLabourCost.EndEdit();
        }


        private int GetLastRowInGridForSpecilaWKName(string strWKID)
        {
            bool blnFind = false;
            foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
            {
                if (CvtFunc.ToString(dgvRow.Cells["WKID"].Value) == strWKID)
                {
                    blnFind = true;
                }
                else
                {
                    if (blnFind) return dgvRow.Index;
                }
            }
            return this.dgvLabourCost.Rows.Count-1;

        }

        private void btnUnApproval_Click(object sender, EventArgs e)
        {
            Control con = sender as WP.Controls.TextRadioBox;
            if (con == null) return;
            string strSQL = "select * from muser where username='"+ SysVar.UserName +"'";
            DataRow drAppro = mdbcon.GetDataFirstRow(strSQL);
            if (drAppro != null)
            {
                utrapproval1.Text = "No";
                txtapprovalPerson1.Text = "";
                datApprovalDate1.Value = "";
                datApprovalDate1.Text = "";
            }
            this.formStatus = FormStatus.Update;
        }

        private void FillTree()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select CategoryID,CategoryName from rmCategory order by CategoryID";
            DataTable dtItem = dbcon.GetDataTable(strSQL);
            foreach (DataRow drType in dtItem.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drType["CategoryID"]) + "-" + CvtFunc.ToString(drType["CategoryName"]));
                this.tvTree.Nodes.Add(tvNode);
            }
            dbcon.CloseCon(); ;
        }

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string strMaterialID = "";
            strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
            //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
            string strCond = " CategoryID ='" + strMaterialID + "'";
            ShowOverViewGrid(strCond);
        }

        private void ShowOverViewGrid(string strWhereCondition)
        {
            string strSql = ""; string strOrderBy = "";
            if (dgList.Sql.Trim() == "")
                strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            else
                strSql = dgList.Sql;

            if (strWhereCondition != "")
            {
                strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
                strSql = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain) + " where " + strWhereCondition;
                //strSql += strOrderBy;
            }
            string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            //mstrWhereCondition = strWhere + (strOrderBy == "" ? "" : strOrderBy);
            this.dgList.Sql = strSql;
        }

        private void SetApprovalControlEnable()
        {
            utrapproval1.Enabled = false; txtapprovalPerson1.Enabled = false; datApprovalDate1.Enabled = false;
            utrapproval2.Enabled = false; txtapprovalPerson2.Enabled = false; datApprovalDate2.Enabled = false;
            utrapproval3.Enabled = false; txtapprovalPerson3.Enabled = false; datApprovalDate3.Enabled = false;
            utrapproval4.Enabled = false; txtapprovalPerson4.Enabled = false; datApprovalDate4.Enabled = false;
            utrapproval5.Enabled = false; txtapprovalPerson5.Enabled = false; datApprovalDate5.Enabled = false;

            string strSQL="select * from mUser where username= '"+ SysVar.UserName + "'";
            DataRow drApproval = mdbcon.GetDataFirstRow(strSQL);
            if (drApproval != null)
            {
                if (CvtFunc.ToBoolean(drApproval["approval1"])) utrapproval1.Enabled = true;
                if (CvtFunc.ToBoolean(drApproval["approval2"])) utrapproval2.Enabled = true;
                if (CvtFunc.ToBoolean(drApproval["approval3"])) utrapproval3.Enabled = true;

                if (CvtFunc.ToBoolean(drApproval["approval4"]))
                {
                    if (   CvtFunc.ToBoolean(utrapproval1.Text) 
                        && CvtFunc.ToBoolean(utrapproval2.Text)
                        && CvtFunc.ToBoolean(utrapproval3.Text))
                    {
                        utrapproval4.Enabled = true;
                        if (!CvtFunc.ToBoolean(utrapproval4.Text))
                        {
                            if (CvtFunc.ToBoolean(drApproval["approval3"]))  utrapproval3.Enabled = true;
                        }
                        else
                        {
                            utrapproval3.Enabled = false;
                        }
                        utrapproval2.Enabled = false;
                        utrapproval1.Enabled = false; 
                    }                    
                }

                if (CvtFunc.ToBoolean(drApproval["approval5"]))
                {
                    if (CvtFunc.ToBoolean(utrapproval1.Text)
                           && CvtFunc.ToBoolean(utrapproval2.Text)
                           && CvtFunc.ToBoolean(utrapproval3.Text)
                           && CvtFunc.ToBoolean(utrapproval4.Text))
                    {
                        utrapproval5.Enabled = true;
                        if (!CvtFunc.ToBoolean(utrapproval5.Text))
                        {
                            if (CvtFunc.ToBoolean(drApproval["approval4"]))  utrapproval4.Enabled = true;
                        }
                        else
                        {
                            utrapproval4.Enabled = false;
                        }
                        utrapproval3.Enabled = false;
                        utrapproval2.Enabled = false;
                        utrapproval1.Enabled = false; 
                    }  
                }
            }
        }

        private void ApprovalCategoryBOM( WP.Controls.TextRadioBox con )
        {
            string strOperType = "";
            if (con.Name !=null )
            {
                if (con.Name == utrapproval1.Name )
                {
                    if (CvtFunc.ToBoolean(utrapproval1.Text))
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval1=1,approvalPerson1='{0}',approvalDate1='{1}' where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson1.Text = SysVar.UserName;
                        datApprovalDate1.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                        strOperType = "一级审核";
                    }
                    else if (CvtFunc.ToBoolean(utrapproval1.Text) == false)
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval=0, approvalDate=null , approval1=0,approvalPerson1='',approvalDate1=null where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson1.Text = "";
                        datApprovalDate5.Text = "";
                        strOperType = "一级反审核";
                    }
                }
                else if (con.Name == utrapproval2.Name)
                {
                    if (CvtFunc.ToBoolean(utrapproval2.Text))
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval2=1,approvalPerson2='{0}',approvalDate2='{1}' where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson2.Text = SysVar.UserName;
                        datApprovalDate2.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                        strOperType = "二级审核";
                    }
                    else if (CvtFunc.ToBoolean(utrapproval2.Text) == false)
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval=0, approvalDate=null , approval2=0,approvalPerson2='',approvalDate2=null where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson2.Text = "";
                        datApprovalDate2.Text = "";
                        strOperType = "二级反审核";
                    }
                }
                else if (con.Name == utrapproval3.Name)
                {
                    if (CvtFunc.ToBoolean(utrapproval3.Text))
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval3=1,approvalPerson3='{0}',approvalDate3='{1}' where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson3.Text = SysVar.UserName;
                        datApprovalDate3.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                        strOperType = "三级审核";
                    }
                    else if (CvtFunc.ToBoolean(utrapproval3.Text) == false)
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval=0, approvalDate=null , approval3=0,approvalPerson3='',approvalDate3=null where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson3.Text = "";
                        datApprovalDate3.Text = "";
                        strOperType = "三级反审核";
                    }
                }
                else if (con.Name == utrapproval4.Name)
                {
                    if (CvtFunc.ToBoolean(utrapproval4.Text))
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval4=1,approvalPerson4='{0}',approvalDate4='{1}' where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson4.Text = SysVar.UserName;
                        datApprovalDate4.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                        this.formStatus = FormStatus.Query;
                        frmParameter.FillContent(this.m_lRecId.ToString());
                        strOperType = "四级审核";
                    }
                    else if (CvtFunc.ToBoolean(utrapproval4.Text) == false)
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval=0, approvalDate=null , approval4=0,approvalPerson4='',approvalDate4=null where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson4.Text = "";
                        datApprovalDate4.Text = "";
                        strOperType = "四级反审核";
                    }
                }
                else if (con.Name == utrapproval5.Name)
                {
                    if (CvtFunc.ToBoolean(utrapproval5.Text))
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval=1, approvalDate='{1}' , approval5=1,approvalPerson5='{0}',approvalDate5='{1}' where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson5.Text = SysVar.UserName;
                        datApprovalDate5.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                        this.formStatus = FormStatus.Query;
                        frmParameter.FillContent(this.m_lRecId.ToString());
                        strOperType = "五级审核";
                    }
                    else if (CvtFunc.ToBoolean(utrapproval5.Text) == false)
                    {
                        string strSQL = "update rmCategorySetBOMHdr set approval=0, approvalDate=null , approval5=0,approvalPerson5='',approvalDate5=null where RecID='{2}'";
                        strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                        mdbcon.ExecuteSql(strSQL);
                        txtapprovalPerson5.Text = "";
                        datApprovalDate5.Text = "";
                        strOperType = "五级反审核";
                    }
                }
                frmParameter.FillContent(this.m_lRecId.ToString());
                AddApproHisory(this.RecID.ToString(), strOperType, mdbcon);
                SetControlByApproLevel();
            }
        }

        public bool AddApproHisory(string strKeyID, string strOperType, DBAccess dbcon)
        {
            string strSQL = "Insert  Into mApproHisory(UserName,OperDate,OperType,KeyID,TableType)";
            strSQL += "VALUES ( '" + SysVar.UserName + "', getdate(), '" + strOperType + "', '" + strKeyID + "', '" + frmApprovalHistory.TableType.CategoryBOM + "' )";
            dbcon.ExecuteSql(strSQL);
            return true;
        }

        private void SetControlByApproLevel()
        {
            if (CvtFunc.ToBoolean(utrapproval.Text) || CvtFunc.ToBoolean(utrapproval4.Text) || CvtFunc.ToBoolean(utrapproval5.Text))
            {
                this.formStatus = FormStatus.Query;
                grpApproval.Enabled = true;
                datApprovalDate.Enabled = true;
                txtapprovalPerson.Enabled = false;
                datApprovalDate.Enabled = false;
                txtRemark.Enabled = false;
                txtWorkCost.Enabled = false;
            }
            //else
            {
                if (CvtFunc.ToBoolean(utrapproval1.Text))
                {
                    dgvBOM.ReadOnly = true;
                    dgvBOM.Columns[(int)DtlCol.DelButton].Visible = false;
                    
                    if (this.tbcMain.SelectedTab == tbpBOM)
                    {
                        this.btnTallyCalculate.Enabled = false;
                        btnAddLine.Enabled = false;
                    }
                    else if ( this.formStatus == FormStatus.Update && this.tbcMain.SelectedTab == tbpOtherCost ) 
                    {
                        this.btnTallyCalculate.Enabled = true ;
                    }
                   
                }
                if (CvtFunc.ToBoolean(utrapproval2.Text))
                {
                    dgvLabourCost.ReadOnly = true;
                    dgvLabourCost.Columns[(int)LabourCostCol.DelButton].Visible = false;
                    if (this.tbcMain.SelectedTab == tbpOtherCost)
                    {
                        btnAddLine.Enabled = false;
                        this.btnTallyCalculate.Enabled = false;
                        
                    }
                }
                else
                {
                    dgvLabourCost.ReadOnly = false ;
                    dgvLabourCost.Columns[(int)LabourCostCol.DelButton].Visible = true ;
                    if (this.tbcMain.SelectedTab == tbpOtherCost)
                    {
                        btnAddLine.Enabled = true ;
                    }
                }
                if (CvtFunc.ToBoolean(utrapproval3.Text))
                {

                }
                if (CvtFunc.ToBoolean(utrapproval4.Text))
                {

                }
                if (CvtFunc.ToBoolean(utrapproval5.Text))
                {

                }
                txtapprovalPerson.Enabled = true;
                datApprovalDate.Enabled = true;
                txtRemark.Enabled = true;
                txtWorkCost.Enabled = true;
                
            }
        }

        private void btnApprovalHistory_Click(object sender, EventArgs e)
        {
            string strRecID = this.RecID.ToString() ;
            frmApprovalHistory frmHist = new frmApprovalHistory(mdbcon, frmApprovalHistory.TableType.CategoryBOM, strRecID);
            frmHist.Text = "审核历史记录";
            frmHist.ShowDialog(); 
        }
    }
}
